package com.wk.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.sun.deploy.util.StringUtils;
import com.wk.springframework.beans.PropertyValue;
import com.wk.springframework.beans.PropertyValues;
import com.wk.springframework.beans.factory.*;
import com.wk.springframework.common.exception.BeanException;
import com.wk.springframework.beans.factory.config.BeanDefinition;
import com.wk.springframework.beans.factory.config.BeanPostProcessor;
import com.wk.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 很有能力的一个bean工厂哦
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object obj;
        try {
//            obj = beanDefinition.getBeanClass().newInstance();
            obj = createBeanInstance(beanName, beanDefinition, args);
            applyPropertyValues(beanName,obj, beanDefinition );
            // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
            obj = initializeBean(beanName, obj, beanDefinition);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 注册实现了 DisposableBean 接口的 Bean 对象
        registerDisposableBeanIfNecessary(beanName, obj, beanDefinition);

        addSingleton(beanName, obj);
        return obj;
    }

    private void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }

    }

    protected  Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (bean instanceof BeanClassLoaderAware){
            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
        }

        if (bean instanceof BeanNameAware){
            ((BeanNameAware) bean).setBeanName(beanName);
        }

        if (bean instanceof BeanFactoryAware){
            ((BeanFactoryAware) bean).setBeanFactory(this);
        }


        // 1. 执行 BeanPostProcessor Before 处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 待完成内容：invokeInitMethods(beanName, wrappedBean, beanDefinition);
        try {

            invokeInitMethods(beanName, wrappedBean, beanDefinition);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 2. 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        return wrappedBean;
    }

    private void invokeInitMethods(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception {
        if (bean instanceof InitializingBean) {
            ((InitializingBean) bean).afterPropertiesSet();
        }
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)){
            Method method = beanDefinition.getBeanClass().getMethod(initMethodName);
            if (Objects.isNull(method)) throw new BeanException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
            method.invoke(bean);
        }

    }

    private Object applyBeanPostProcessorsAfterInitialization(Object bean, String beanName) {
        Object wrapperBean = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(wrapperBean, beanName);
            if (null == current) return wrapperBean;
            wrapperBean = current;
        }
        return wrapperBean;
    }

    private Object applyBeanPostProcessorsBeforeInitialization(Object bean, String beanName) {
        Object wrapperBean = bean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(wrapperBean, beanName);
            if (null == current) return wrapperBean;
            wrapperBean = current;
        }
        return wrapperBean;
    }


    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) {

                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference) {
                    // A 依赖 B，获取 B 的实例化
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeanException("Error setting property values：" + beanName);
        }
    }

    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Class beanClass = beanDefinition.getBeanClass();
        Constructor targetCtor = null;
        try {
            Constructor[] declaredConstructor = beanClass.getDeclaredConstructors();
            for (Constructor constructor : declaredConstructor) {
                if (constructor != null && constructor.getParameterTypes().length == args.length) {
                    targetCtor = constructor;
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, targetCtor, args);
    }

    protected InstantiationStrategy getInstantiationStrategy() {
        return this.instantiationStrategy;
    }


}
